package gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferStrategy;

import javax.swing.JComponent;
import javax.swing.JFrame;

import kj.dsp.KJDigitalSignalProcessor;

public class VisualOverlay implements KJDigitalSignalProcessor {

	private final Color background = new Color(0, 0, 0, 30);

	private final JFrame host;
	private long lastMove = System.currentTimeMillis();

	public VisualOverlay(JFrame host) {
		this.host = host;
		host.createBufferStrategy(2);
		addListenerRecursive(host.getContentPane());
	}

	private void addListenerRecursive(Component comp) {
		comp.addMouseMotionListener(adapter);
		// comp.addMouseWheelListener(adapter);
		if (comp instanceof JComponent) {
			JComponent j = (JComponent) comp;
			for (Component c : j.getComponents()) {
				addListenerRecursive(c);
			}
		}
	}

	private final MouseAdapter adapter = new MouseAdapter() {

		@Override
		public void mouseMoved(MouseEvent e) {
			lastMove = System.currentTimeMillis();
		}

		@Override
		public void mouseDragged(MouseEvent e) {
			lastMove = System.currentTimeMillis();
		}

	};

	private float[] stereoMerge(float[] pLeft, float[] pRight) {
		for (int a = 0; a < pLeft.length; a++) {
			pLeft[a] = (pLeft[a] + pRight[a]) / 2.0f;
		}
		return pLeft;
	}

	private void drawScope(Graphics g, float[] pSample) {
		int height_2 = host.getHeight() >> 1;
		int width = host.getWidth();
		g.setColor(Color.blue);
		int last = (int) (pSample[0] * height_2) + height_2;
		float widthPerSample = 1.0f * width / pSample.length;
		float x = 0;
		for (int c = 0; c < pSample.length; c++) {
			int current = (int) (pSample[c] * height_2) + height_2;
			g.drawLine((int) x, last, (int) (x + widthPerSample), current);
			last = current;
			x += widthPerSample;
		}

	}

	@Override
	public void process(float[] pLeft, float[] pRight, float pFrameRateRatioHint) {
		BufferStrategy bf = host.getBufferStrategy();
		Graphics g = bf.getDrawGraphics();
		int timePassed = (int) (System.currentTimeMillis() - lastMove);
		float percent = (timePassed - 5000) / 6000.0f;
		if (percent < 1) {
			host.paintAll(g);
			if (timePassed > 5000) {
				g.setColor(new Color(0, 0, 0, (int) (255 * percent)));
				g.fillRect(0, 0, host.getWidth(), host.getHeight());
			}
		} else {
			g.setColor(new Color(0, 0, 0, 30));
			g.fillRect(0, 0, host.getWidth(), host.getHeight());
		}

		drawScope(g, stereoMerge(pLeft, pRight));
		g.dispose();
		bf.show();
		// host.repaint();
	}

}
